#!/bin/env pypy

"""
Wrapper around the Control-FREEC copy number analysis software.

Usage:
  freec <test_bam> [<control_bam>] -o OUTPUT_DIR

Options:
  -h --help   Show this screen.
"""

from __future__ import print_function
import sys, subprocess, docopt, re, os, pwd, datetime, time
from pypette import zopen, shell, mkdir
from pypette import info, error, shell_stdout
import numpypy as np




common_config = """
[general]
breakPointThreshold=0.8
breakPointType=2
chrLenFile=/data/csb/organisms/homo_sapiens/hg19.chrom.sizes
contamination=0.8
contaminationAdjustment=TRUE
gemMappabilityFile=/data/csb/tools/FREEC-6.4/out100m2_hg19.gem
minCNAlength=3
maxThreads=4
outputDir=%s
ploidy=2
sex=XY
step=5000
window=5000

[sample]
mateFile=%s
inputFormat=BAM
mateOrientation=FR

[control]
mateFile=%s
inputFormat=BAM
mateOrientation=FR
"""



#############################
# FREEC WITH CONTROL SAMPLE #
#############################

def freec_with_control(test_bam_path, control_bam_path, output_dir):
	output_dir = os.path.abspath(output_dir)
	mkdir(output_dir)
	config_path = output_dir + '/config.txt'
	with open(config_path, 'w') as config:
		config.write(common_config %
			(output_dir, test_bam_path, control_bam_path))
	
	shell('/data/csb/tools/FREEC-6.4/freec -conf %s' % config_path)







#######################
# COMMAND LINE PARSER #
#######################

if __name__ == '__main__':
	args = docopt.docopt(__doc__)
	print(args)
	if args['<control_bam>']:
		freec_with_control(args['<test_bam>'], args['<control_bam>'],
			output_dir=args['OUTPUT_DIR'])

